﻿@model OnlineEducation.Data.Entities.TeachingPlan
@{
    IEnumerable<OnlineEducation.Data.Entities.Course> courses = ViewBag.Courses as IEnumerable<OnlineEducation.Data.Entities.Course>;

    List<OnlineEducation.Data.Entities.ApplicationUser> teachers = ViewBag.Teachers as List<OnlineEducation.Data.Entities.ApplicationUser>;

    IEnumerable<SelectListItem> weekdaysItems = ViewBag.WeekdayItems as IEnumerable<SelectListItem>;
}

@section Styles{

    <link href="~/assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css" />
    <style>
        .radio label {
            padding-left: 4px;
        }
    </style>
}

<!-- Start Content-->
<div class="container-fluid">

    <!-- start page title -->
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">

                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="javascript: void(0);"><i class="fa fa-map-marker-alt"></i></a></li>
                        <li class="breadcrumb-item"><a href="javascript: void(0);">教学计划</a></li>
                        <li class="breadcrumb-item active">添加</li>
                    </ol>
                </div>
                <h4 class="page-title">添加教学计划</h4>
            </div>
        </div>
    </div>
    <!-- end page title -->
    <form id="teachingplan">

        <div class="row">

            <div class="col-12">

                <div class="card-box ">
                    <h5 class="text-uppercase mt-0 bg-light p-2">基础信息</h5>
                    <input asp-for="Id" type="hidden" value="@Model.Id" />
                    @*<div class="form-group">
                            <label for="Name"><span class="text-danger">*</span>计划名称</label>
                            <input type="text" asp-for="Name" class="form-control" placeholder="输入计划名称">
                            <span asp-validation-for="Name" class="text-danger"></span>
                        </div>*@

                    <div class="form-group">
                        <label for="CourseId"><span class="text-danger">*</span>课程名称 </label>
                        <select asp-for="CourseId" class="form-control select2" asp-items="OnlineEducation.Constants.CodeHelper.GetListItems(courses)"></select>
                        <span asp-validation-for="CourseId" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label for="BeginTime"><span class="text-danger">*</span>开始日期 </label>
                        <input type="text" asp-for="BeginTime" class="form-control" placeholder="输入课程开始日期">
                        <span asp-validation-for="BeginTime" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label for="TeacherId"><span class="text-danger">*</span>教师 </label>
                        <select asp-for="TeacherId" class="form-control select2" asp-items="OnlineEducation.Constants.CodeHelper.GetListItems(teachers)"></select>
                        <span asp-validation-for="TeacherId" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label for="notification">课程公告</label>
                        <textarea type="text" asp-for="Notification" class="form-control" placeholder="输入公告" rows="3"></textarea>
                    </div>
                </div> <!-- end col-->

            </div>

            <div class="col-12">

                <div class="card-box">
                    <h5 class="text-uppercase mt-0 mb-3 bg-light p-2">课程安排</h5>
                    <div class="form-group pl-1">
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption4" value="4" name="TeachingTimeOption" checked>
                            <label for="TeachingTimeOption4"> 每4周循环 </label>
                        </div>
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption3" value="3" name="TeachingTimeOption">
                            <label for="TeachingTimeOption3"> 每3周循环 </label>
                        </div>
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption2" value="2" name="TeachingTimeOption">
                            <label for="TeachingTimeOption2"> 每2周循环 </label>
                        </div>
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption1" value="1" name="TeachingTimeOption">
                            <label for="TeachingTimeOption1"> 每周循环 </label>
                        </div>
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption0" value="0" name="TeachingTimeOption">
                            <label for="TeachingTimeOption0"> 每天循环 </label>
                        </div>
                        <div class="radio form-check-inline">
                            <input type="radio" id="TeachingTimeOption-1" value="-1" name="TeachingTimeOption">
                            <label for="TeachingTimeOption-1"> 自定义 </label>
                        </div>
                    </div>
                    <div class="form-group pl-1 float-right" style="margin-top:-10px">
                        <div class="checkbox form-check-inline ">
                            <input type="checkbox" asp-for="IncludeWeekend" disabled />
                            <label for="includeWeekend"> 包含周末 </label>
                        </div>
                        <div class="checkbox form-check-inline  ">
                            <input type="checkbox" asp-for="IncludeHoliday" disabled />
                            <label for="includeHoliday"> 包含国假 </label>
                        </div>
                        <div class="checkbox form-check-inline  ">
                            <input type="checkbox" asp-for="IncludeWSVacation" disabled />
                            <label for="includeWSVacation"> 包含寒暑假 </label>
                        </div>
                    </div>
                </div>
                <div class="form-group form-inline">
                    <label for="product-meta-keywords" class="m-1">上课时间</label>
                    <select asp-for="TeachingTimeWeekday" class="form-control select2  m-1" asp-items="weekdaysItems"></select>
                    <input type="text" asp-for="TeachingTimeOptionStartTime" class="form-control m-1" placeholder="输入默认开始时间" />
                </div>
            </div> <!-- end col-->

        </div> <!-- end col-->

        <div class="col-12">
            <div class="card-box mb-0">
                <h5 class="text-uppercase mt-0 mb-3 bg-light p-2">课时列表</h5>
                <div class="table-responsive" data-pattern="priority-columns" data-add-focus-btn="false" data-add-display-all-btn="false" data-add-display-btn="false">
                    <table class="table table-hover m-0 table-centered dt-responsive nowrap" id="datatable" style="width:100%">
                        <thead>
                            <tr>
                                <th data-priority="1" width="10%">序号</th>
                                <th data-priority="1" width="10%">标题</th>
                                <th data-priority="1" width="10%">章-节</th>
                                <th  data-priority="1" width="10%">时长</th>
                                <th  data-priority="1" width="10%">开始时间</th>

                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>

                </div>
            </div> <!-- end card-box -->
        </div>


        <div class="col-12">
            <div class="text-right card-box mb-3">
                <button type="button" class="btn w-sm btn-secondary  waves-effect">重置</button>
                <button type="button" id="btnSubmit" class="btn w-sm btn-primary waves-effect waves-light">发布</button>

            </div>
        </div>


    </form>

    <!-- end row -->


    @section Scripts{
        @await Html.PartialAsync("_ValidationScriptsPartial")
        <script src="~/assets/libs/moment/moment.min.js"></script>
        <script src="~/assets/libs/flatpickr/flatpickr.min.js"></script>
        <script src="~/assets/libs/flatpickr/zh.js"></script>
        <script>

            Ladda.bind('.btn', { timeout: 1000 });

            var table;

            $(function () {

                var holidays = {};

                $('#CourseId,#TeacherId').select2({ width: '100%' });

                $("#BeginTime").flatpickr({ enableTime: false, dateFormat: "Y-m-d", locale: "zh" });

                $("#TeachingTimeOptionStartTime").flatpickr({ enableTime: true, noCalendar: true, dateFormat: "H:i", locale: "zh" });

                $(".lesson-actual-start-time").flatpickr({ enableTime: true, noCalendar: false, dateFormat: "Y-m-d H:i", locale: "zh" });

                $('#CourseId').change(function () {

                    if (table) {

                        table.draw();

                    }

                });

                $("#btnSubmit").click(function () {

                    var form = $("#teachingplan");
                    form.removeData('validator');
                    form.removeData('unobtrusiveValidation');
                    $.validator.unobtrusive.parse(form);


                    if ($(form).valid()) {
                        var data = $(form).serializeJSON();



                        data.IncludeWeekend = $("#IncludeWeekend").prop("checked");
                        data.IncludeHoliday = $("#IncludeHoliday").prop("checked");
                        data.IncludeWSVacation = $("#IncludeWSVacation").prop("checked");

                        data.TeachingPlanItems = new Array();
                        console.log(data);
                        $("input[name^=lesson_id]").each(function (index, element) {

                            var item = $(element).data();
                            console.log(item.id);
                            data.TeachingPlanItems.push({
                                LessonId: item.id,
                                BeginTime: $(element).val()
                            });


                        });

                        data = JSON.stringify(data);
                        console.log(data);
                        $.ajax({
                            type: 'POST',
                            url: '/TeachingPlan/Save',
                            data: data,
                            contentType: 'application/json',
                            success: function (data) {
                                if (data.success) {

                                    ShowMessage(data.message);
                                    setTimeout(function () {
                                        window.location.href = "/TeachingPlan/Index";
                                    }, 2000);

                                } else {
                                    ShowMessageError(data.message);
                                }
                            } 
                        });

                    }
                    return false;




                });

                $("#TeachingTimeOption0,#TeachingTimeOption-1").click(function () {

                    $("#TeachingTimeWeekday").prop("disabled", true);

                });

                $("#TeachingTimeOption1,#TeachingTimeOption2,#TeachingTimeOption3,#TeachingTimeOption4").click(function () {

                    $("#TeachingTimeWeekday").prop("disabled", false);
                });

                $("#TeachingTimeOption-1").click(function () {

                    $("#TeachingTimeOptionStartTime").prop("disabled", true);

                });

                $("#TeachingTimeOption0,#TeachingTimeOption1,#TeachingTimeOption2,#TeachingTimeOption3,#TeachingTimeOption4").click(function () {

                    $("#TeachingTimeOptionStartTime").prop("disabled", false);

                });


                table = $('#datatable').DataTable({
                    "oLanguage": {
                        "sLengthMenu": "每页显示 _MENU_ 条记录",
                        "sZeroRecords": "对不起，没有匹配的数据",
                        "sInfo": "第 _START_ - _END_ 条 / 共 _TOTAL_ 条数据",
                        "sInfoEmpty": "没有匹配的数据",
                        "sInfoFiltered": "(数据表中共 _MAX_ 条记录)",
                        "sProcessing": "正在加载中...",
                        "sSearch": "全文搜索：",
                        "oPaginate": {
                            "sFirst": "第一页",
                            "sPrevious": " 上一页 ",
                            "sNext": " 下一页 ",
                            "sLast": " 最后一页 "
                        }
                    },
                    drawCallback: function () {
                        $(".dataTables_paginate > .pagination").addClass("pagination-rounded");
                        $(".lesson-actual-start-time").flatpickr({ enableTime: true, noCalendar: false, dateFormat: "Y-m-d H:i", locale: "zh" });
                    },

                    "responsive": false,
                    "lengthChange": false,
                    "searching": false,
                    "paging": false,
                    "ordering": false,
                    //"order": [[0, 'asc']],
                    //"aoColumnDefs": [{ "bSortable": false, "aTargets": [1, 2, 3] }],
                    "serverSide": true,
                    ajax: {
                        url: '/TeachingPlan/GetLessonsByCourseId',
                        type: 'POST',
                        async: true,
                        //headers: {
                        //    "XSRF-TOKEN": document.querySelector('[name="__RequestVerificationToken"]').value
                        //},
                        data: function (data) {
                            data.AdditionalValues = [$("#CourseId").val()];
                            return {
                                param: data
                            };
                        },
                        complete: function () {
                            FillLessonStartDate();
                            $(".lesson-actual-start-time").flatpickr({ enableTime: true, noCalendar: false, dateFormat: "Y-m-d H:i", locale: "zh" });
                        },
                        error: function (jqXHR) {

                            HandleGlobalException(jqXHR);

                        }


                    },

                    columns: [
                        {
                            title: "序号",
                            data: "Sequence",
                            name: "Sequence",

                        },
                        {
                            title: "标题",
                            data: "Title",
                            name: "Title"
                        },
                        {
                            title: "章-节",
                            render: function (data, type, row) {

                                return row["Chapter"] + '-' + row["Section"];
                            }
                        },
                        {
                            title: "时长",
                            data: "Duration",
                            render: function (data, type, row) {

                                return data + "分";
                            }
                        },
                        {
                            title: "开始时间",
                            render: function (data, type, row) {

                                var id = row["Id"];

                                var html = "<input type='text' class='form-control lesson-actual-start-time' data-val='true' data-val-required='开始时间不能为空' data-id='" + id + "' id='lesson_id_" + id + "' name='lesson_id_" + id + "' placeholder='输入课时开始时间'>";
                                html += "<span class='text-danger field-validation-valid' data-valmsg-for='" + "lesson_id_" + id + "' data-valmsg-replace='true'></span>";
                                return html;

                            }
                        }

                    ]


                });


                table.on('responsive-display', function (e, datatable, row, showHide, update) {
                    $(".lesson-actual-start-time").flatpickr({ enableTime: true, noCalendar: false, dateFormat: "Y-m-d H:i", locale: "zh" });
                });

                $.get("/TeachingPlan/GetHolidays").
                    done(function (res) {
                        holidays = res.data;

                        holidays = $.parseJSON(JSON.stringify(res.data));

                        console.log(new Date(holidays[0].From).getFullYear());
                        console.log(new Date(holidays[0].From));

                    });


                $('#TeachingTimeWeekday').change(function () {

                    FillLessonStartDate();

                });

                $("input[name=TeachingTimeOption").click(function () {
                    FillLessonStartDate();

                });

                $("#TeachingTimeOptionStartTime").change(function () {
                    FillLessonStartDate();
                })

                Date.prototype.Format = function (fmt) {
                    var o = {
                        "M+": this.getMonth() + 1,                 //月份
                        "d+": this.getDate(),                    //日
                        "h+": this.getHours(),                   //小时
                        "m+": this.getMinutes(),                 //分
                        "s+": this.getSeconds(),                 //秒
                        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                        "S": this.getMilliseconds()             //毫秒
                    };
                    if (/(y+)/.test(fmt))
                        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                        if (new RegExp("(" + k + ")").test(fmt))
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                }




            });
            function addDays(date, days) {
                var result = new Date(date);
                result.setDate(result.getDate() + days);
                return result;
            }

            function FillLessonStartDate() {

                var ids = '';

                if (!$("#BeginTime").val()) return;

                var course_start_date = new Date($("#BeginTime").val());

                var course_day = course_start_date.getDay();

                if (course_day == 0) {
                    course_day = 7;
                }

                var prefer_day = $("#TeachingTimeWeekday").val();

                var lesson_first_date;

                if (prefer_day) {

                    var diff = prefer_day - (course_day);

                    if (diff < 0) diff = diff + 7;

                    lesson_first_date = addDays(course_start_date, diff);
                }
                else {
                    lesson_first_date = course_start_date;
                }

                var time = $("#TeachingTimeOptionStartTime").val();

                if (time) {

                    var hm = time.split(":");

                    lesson_first_date.setHours(parseInt(hm[0]));

                    lesson_first_date.setMinutes(parseInt(hm[1]));
                } else {
                    return;
                }

                var i = 0;

                var next_lesson_date;

                $("input[name^=lesson_id_]").each(function (index, element) {

                    var id = $(this).data().id;

                    var v = $("input[name^=TeachingTimeOption]:checked").val();

                    if (v == -1) return;

                    if (i == 0) {

                        next_lesson_date = lesson_first_date;

                        $(this).val(next_lesson_date.Format("yyyy-MM-dd hh:mm"));
                    }
                    else {
                        if (v == 0) {
                            next_lesson_date = addDays(next_lesson_date, 1);
                        } else {
                            next_lesson_date = addDays(next_lesson_date, parseInt(v) * 7);
                        }


                        $(this).val(next_lesson_date.Format("yyyy-MM-dd hh:mm"));
                    }

                    i = i + 1;

                    console.log(next_lesson_date);


                });

                return "";

            }

        </script>
    }
